import {Message} from "element-ui";
import axios from "axios";
import router from "@/router";

const instance = axios.create({
    baseURL: "http://localhost:3000", timeout: 5000, // 请求超时时间 超过5s 请求超过5s这个请求就失效
});
//在连接端口之前，通过axios拦截器添加token，保证拥有获取数据的权限.
instance.interceptors.request.use(config => {
    // console.log("请求拦截器", {config});
    const {url} = config
    // console.log("url", url)
    // //为请求头对象添加token验证的Authorization字段
    // config.headers.Authorization = window.sessionStorage.getItem('Token')
    // console.log("config.headers.Authorization", config.headers.Authorization);

    const token = window.sessionStorage.getItem('Token')
    if (token) {
        config.headers["Authorization"] = token;
    } else {
        if (url !== '/login' || url !== '/register') {
            // console.log("url", url)
            router.push('/login').then(r => {
                // console.log({r})
            })
        }

    }
    return config
})


// 响应拦截器
instance.interceptors.response.use(response => {
    // console.log({response})
    if (!response) {
        Message.error("网络错误")
        return
    }
    const {data: {code, msg, data}} = response
    if (code === 201) Message.success(msg)

    return response.data


}, error => {
    let {data: {code, data, isSuccess, msg}} = error.response
    Message.error(msg)
    return Promise.reject(error)

})


export default instance